package com.jxwifi.cloud.quickclean.upgrade;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

/**
 * 获取项目版本号与版本名称
 * @author 
 *
 */
public class UpgradeCodeName {

	/**
	 * 获取版本号
	 * @param context
	 * @return
	 */
	public static int getVerCode(Context context) {
        int verCode = -1;  
        try {  
            //注意："com.example.try_downloadfile_progress"对应AndroidManifest.xml里的package="……"部分  
            verCode = context.getPackageManager().getPackageInfo(  
                    "com.jxwifi.cloud.quickcleanserver", 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e("msg",e.getMessage());
        }  
        return verCode;  
    }  
	 /**
	  * 获取版本名称
	  * @param context
	  * @return
	  */
	 public static String getVerName(Context context) {
	        String verName = "";
	        try {  
	            verName = context.getPackageManager().getPackageInfo(  
	                    "com.jxwifi.cloud.quickclean", 0).versionName;
	        } catch (NameNotFoundException e) {
	            Log.e("msg",e.getMessage());
	        }  
	        return verName;     
	}

	/**
	 * 版本号比较
	 *
	 * @param version1
	 * @param version2
	 * @return 0代表相等，1代表version1(本地)大于version2（服务器），-1代表version1小于version2
	 */
	public static int compareVersion(String version1, String version2) {
		if (version1.equals(version2)) {
			return 0;
		}
		String[] version1Array = version1.split("\\.");
		String[] version2Array = version2.split("\\.");
		Log.d("HomePageActivity", "version1Array=="+version1Array.length);
		Log.d("HomePageActivity", "version2Array=="+version2Array.length);
		int index = 0;
		// 获取最小长度值
		int minLen = Math.min(version1Array.length, version2Array.length);
		int diff = 0;
		// 循环判断每位的大小
		Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
		while (index < minLen
				&& (diff = Integer.parseInt(version1Array[index])
				- Integer.parseInt(version2Array[index])) == 0) {
			index++;
		}
		if (diff == 0) {
			// 如果位数不一致，比较多余位数
			for (int i = index; i < version1Array.length; i++) {
				if (Integer.parseInt(version1Array[i]) > 0) {
					return 1;
				}
			}

			for (int i = index; i < version2Array.length; i++) {
				if (Integer.parseInt(version2Array[i]) > 0) {
					return -1;
				}
			}
			return 0;
		} else {
			return diff > 0 ? 1 : -1;
		}
	}
}
